﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace intelliSys.UI.Interaction.MouseGesture
{
    internal class Segment
    {
        public bool IsOnSegment(Win32.Point pt)
        {
            if ((pt.Y <= Start.Y && pt.Y >= End.Y) || (pt.Y >= Start.Y && pt.Y <= End.Y))
            {
                if ((pt.X <= Start.X && pt.X >= End.X) || (pt.X >= Start.X && pt.X <= End.X))
                {
                    if (pt.Y == Slope * pt.X + ExtendedLineInterceptY)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        public bool Intercept(Segment segment)
        {
            if (segment.Slope == Slope)
            {
                if (ExtendedLineInterceptY != segment.ExtendedLineInterceptY)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                Win32.Point intercept;
                if (Slope == 0)
                {
                    intercept = new Win32.Point
                      {
                          X = (int)((ExtendedLineInterceptY - segment.ExtendedLineInterceptY) / segment.Slope),
                          Y = (int)((ExtendedLineInterceptY))
                      };

                }
                else
                {
                    intercept = new Win32.Point
                     {
                         X = (int)((segment.ExtendedLineInterceptY - ExtendedLineInterceptY) / (Slope - segment.Slope)),
                         Y = (int)((segment.ExtendedLineInterceptY * Slope - ExtendedLineInterceptY * segment.Slope) / (Slope - segment.Slope))
                     };
                } if (IsOnSegment(intercept))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        public Win32.Point Start
        {
            get;
            set;
        }
        public Win32.Point End
        {
            get;
            set;
        }
        public double ExtendedLineInterceptY
        {
            get
            {
                try
                {
                    return Start.Y - Slope * Start.X;
                }
                catch (ArithmeticException)
                {
                    return Start.X;
                }
            }
        }
        public double Slope
        {
            get
            {
                if (End.X - Start.X == 0)
                {
                    return double.MaxValue;
                }
                return (End.Y - Start.Y) / (End.X - Start.X);
            }
        }
    }
}
